#include "Timer.h"

namespace SEngine
{

    Timer::Timer()
    {
    }
    
    Timer::~Timer() 
    {
        Release();
    }

    void Timer::Run(int ms, std::function<void(void)> &&fn, bool isOneShot)
    {
        m_timeOut = ms;
        m_timeOutCb = std::move(fn);
        m_isOneShot = isOneShot;
        s_timers.emplace_back(this);
    }

    void Timer::Update(int delta)
    {
        for (auto & timer : s_timers) {
            timer->m_currentTime += delta;
            if (timer->m_currentTime > timer->m_timeOut) {
                timer->m_timeOutCb();
                if (timer->m_isOneShot) {
                    timer->Release();
                } else {
                    timer->m_currentTime = 0;
                }
            }
        }
    }

    void Timer::Release()
    {
        s_timers.erase(std::remove_if(s_timers.begin(), s_timers.end(), [this](Timer * elem) { return elem == this; }), s_timers.end());
    }

} // namespace SEngine
